package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.handler.AlarmExcelDictHandlerImpl;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.AlarmRuleInfo;
import git.soulbgm.service.AlarmRuleInfoService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 告警规则信息控制器
 *
 * @author SoulBGM
 * @date 2022/03/11 10:28
 */
@RestController
@RequestMapping("system/alarmRule")
public class AlarmRuleController extends BaseController {

    private final AlarmRuleInfoService alarmRuleInfoService;
    private final AlarmExcelDictHandlerImpl dictHandler;

    public AlarmRuleController(AlarmRuleInfoService alarmRuleInfoService, AlarmExcelDictHandlerImpl dictHandler) {
        this.alarmRuleInfoService = alarmRuleInfoService;
        this.dictHandler = dictHandler;
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<AlarmRuleInfo> dto, Page<AlarmRuleInfo> queryPage) {
        Page<AlarmRuleInfo> resultPage = alarmRuleInfoService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("export")
    public void export(AlarmRuleInfo info, HttpServletResponse response) {
        List<AlarmRuleInfo> list = alarmRuleInfoService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "告警规则数据", list, AlarmRuleInfo.class, dictHandler);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    @PostMapping("add")
    public Response add(AlarmRuleInfo info) {
        boolean result = alarmRuleInfoService.save(info);
        if (result) {
            alarmRuleInfoService.clearCache();
        }
        return result ? success() : error();
    }

    @PostMapping("remove")
    public Response remove(String ids) {
        boolean result = alarmRuleInfoService.removeByIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()));
        if (result) {
            alarmRuleInfoService.clearCache();
        }
        return result ? success() : error();
    }

    @PostMapping("edit")
    public Response edit(AlarmRuleInfo info) {
        boolean result = alarmRuleInfoService.updateById(info);
        if (result) {
            alarmRuleInfoService.clearCache();
        }
        return result ? success() : error();
    }
}
